//
//  STCommodityTVViewModel.swift
//  StarTimesON
//
//  Created by Toj on 8/19/22.
//  Copyright © 2022 StarTimes. All rights reserved.
//

import UIKit

class STCommodityTVViewModel: NSObject {
    
    private var couponCode = ""
    private var sections: [STCommodityTVSectionModel] = []
    var responseSections: ((_ sections: [STCommodityTVSectionModel])->Void)?
    
    private let provider = STNetwork<STSDVBApi>()
    
    private(set) var selectedCommodity: TVCommodityCellModel? { willSet {
        selectedCommodity?.isSelected = false
        newValue?.isSelected = true
        commoditiesSection.produtctCellModel?.selectedCommodity = newValue
    } didSet {
        setupCommodityData()
        setupPurchaseData()
    } }
    
    var selectedAdditionalCommodity: TVAdditionalCommodityCellModel? { willSet {
        selectedAdditionalCommodity?.isSelected = false
        newValue?.isSelected = true
        purchaseSection.purchaseCellModel?.selectedCommodity = newValue
    } }
    
    // DVB状态改变
    private(set) var dvbState = OTTActivationStatus.none { didSet {
        guard dvbState != oldValue else { return }
        
        NotificationCenter.default.post(name: NSNotification.Name.ServiceRightsDidChange, object: nil)
    } }
    
    private(set) lazy var cardSection: STCommodityTVSectionModel = {
        let section = STCommodityTVSectionModel()
        section.type = .card
        section.footerSize = CGSize(width: STScreenWidth, height: 8)
        section.layoutEdgeinset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
        let width = STScreenWidth - 12 * 2
        let height = width * 170 / 336
        section.cellSize = CGSize(width: width, height: height)
        section.cardCellModel = nil
        return section
    }()
    
    private lazy var commoditiesSection: STCommodityTVSectionModel = {
        let section = STCommodityTVSectionModel()
        section.type = .commodity
        section.footerSize = CGSize(width: STScreenWidth, height: 8)
        return section
    }()
    
    private var purchaseDictionary: [String: TVPurchaseCellModel] = [:]
    private lazy var purchaseSection: STCommodityTVSectionModel = {
        let section = STCommodityTVSectionModel()
        section.type = .purchase
        return section
    }()
    
    private(set) lazy var channelsSection: STCommodityTVSectionModel = {
        let section = STCommodityTVSectionModel()
        section.title = "membership_payment".localized()
        section.type = .payChannel
        section.cellSize = CGSize(width: STScreenWidth, height: 47.ui_scale)
        section.headerSize = CGSize(width: STScreenWidth, height: 32.f_scale + 12)
        return section
    }()
    
    private var commodityCouponCellModels: [String: [TVCouponCellModel]] = [:]
    private(set) lazy var couponSection: STCommodityTVSectionModel = {
        let section = STCommodityTVSectionModel()
        section.type = .coupon
        section.isImage = false
        section.footerSize = CGSize(width: STScreenWidth, height: 8)
        section.cellSize = CGSize(width: STScreenWidth, height: 40.ui_scale)
        return section
    }()
    
    private var serviceSection: STCommodityTVSectionModel = {
        let section = STCommodityTVSectionModel()
        section.type = .services
        
        let width = STScreenWidth - 12 * 2
        section.layoutEdgeinset = UIEdgeInsets(top: 4, left: 12, bottom: 17, right: 12)
        section.cellSize = CGSize(width: width, height: 55)
        section.footerSize = CGSize(width: STScreenWidth, height: 8)
        return section
    }()
    
    private var chargeInfo: TVRechargeInfo?
    private func resetupSections() {
        selectedCommodity = nil
        selectedAdditionalCommodity = nil
        purchaseDictionary = [:]
        commodityCouponCellModels.removeAll()
        sections.removeAll()
        
        let isLinkCard = AppFunctionManager.isUsable(function: .FB_DVB_ACTIVATION)
        if isLinkCard {
            sections.append(cardSection)
            responseCardSection()
        }
        
        // 规格信息
        responseComoditiesSection(smartcardInfo: chargeInfo?.smartcardInfo)
        
        // 加购信息
        responsePurchaseSection(chargeInfo: chargeInfo)
        
        // 支付渠道信息
        responseCommodityChannelSection(orderInf: chargeInfo?.preOrderInfo)
        
        // 优惠券信息
        responseCounponSection(orderInf: chargeInfo?.preOrderInfo)
        
        // 服务项
        responseServicesSection()
        
        // 用户协议
        responseServiceSection()
        
        // 初始化默认规格对应的优惠券
        setupDefaultCommodityAndCoupon()
        
        // 接口返回
        responseSections?(sections)
        
        chargeInfo = nil
    }
}

extension STCommodityTVViewModel {
    private func setupCommodityData() {
        guard let commodity = selectedCommodity else {
            return
        }
        
        // titleTop: 4
        // titleHeight: 40
        // cellHeight: 112
        var height: CGFloat = 156
        if commodity.isDiscount {
            // 36 = 28 + 8
            height += 36
        }
        // amountTitleTop: 4
        // amountTitleHeight: 40
        height += 44
        
        // amountHeight
        let row = ceil(Double(commodity.numbers.count) / 6.0)
        let amountHeight = row * 24 + (row - 1) * 16
        height += amountHeight
        // bottomMargin: 16
        height += 16
        
        let width = STScreenWidth
        commoditiesSection.cellSize = CGSize(width: width, height: height)
    }
    
    private func setupPurchaseData() {
        let selectedCommodityID = selectedCommodity?.id ?? ""
        
        let purchaseCellModel = purchaseDictionary[selectedCommodityID]
        purchaseSection.purchaseCellModel = purchaseCellModel
        purchaseCellModel?.reset()
        selectedAdditionalCommodity = purchaseCellModel?.selectedCommodity
        
        var layoutEdgeinset = UIEdgeInsets.zero
        var footerSize = CGSize.def_cell
        var cellSize = CGSize.def_cell
        if purchaseCellModel != nil {
            layoutEdgeinset = UIEdgeInsets(top: 12, left: 12, bottom: 16, right: 12)
            let width = STScreenWidth-24
            footerSize = CGSize(width: width, height: 8)
            
            var briefHeight: CGFloat = 8 // 上间距
            let brief = purchaseCellModel?.brief ?? ""
            if !brief.isEmpty {
                let briefSize = brief.st_stringHeight(font: 10.to_systemFont, maxWidth: width-24)
                // 文字高度 + 上下间距: 16 = 8 * 2
                briefHeight = briefSize + 16
            }
            // 标题高度 44
            // collectionView高度 100
            // 简介高度
            // 底部间距: 20
            let height = 176 + briefHeight
            
            cellSize = CGSize(width: width, height: height)
        }
        purchaseSection.layoutEdgeinset = layoutEdgeinset
        purchaseSection.footerSize = footerSize
        purchaseSection.cellSize = cellSize
    }
}

extension STCommodityTVViewModel {
    
    /** 一、进入页面接口返回后 规格的一个二次查找 */
    private func setupDefaultCommodityAndCoupon() {
        guard let produtct = commoditiesSection.produtctCellModel else { return }
        // 接口返回默认规格, 如果找不到默认规格, 默认规格是数组第一个
        guard let commodity = produtct.selectedCommodity else { return }
        setupCouponAndNumberIndex(for: commodity)
    }
    
    /** 二、TV进入/ Recharge进入/ 选择规格, 找券
     * 找券: 规格, 数量 确定的前提下 找能用券/ 可用券/ 找不到券
     * 能用券: 有优惠力度最大的券立即使用,
     优惠券模块显示: 优惠金额OFF
     * 可用券: 没有能用券为前提. 某个数量 x 规格可使用 & 优惠条件最低 & 优惠力度最大的券
     利用最大数量对应的金额做边界值匹配, 最大金额能用就肯定可用
     优惠券模块显示: 优惠金额 discount for purchases over 满足条件
     * 找不到券: 没有能用券 & 也没有可用券,
     优惠券模块显示: SELECT
     */
    func setupCouponAndNumberIndex(for commodity: TVCommodityCellModel) {
        selectedCommodity = commodity

        let price = commodity.price
        let numberValue = commodity.selectedNumberValue
        let priceMulriple = Double(numberValue) * price

         // 如果规格有券直接跳出, 没有优惠券找券
         var defalutCoupon = commodity.selectedCouponModel
         if defalutCoupon != nil {
             _ = defalutCoupon?.offPrice(priceMulriple)
             couponSection.couponViewModel?.selectedCouponModel = defalutCoupon
             return
         }

        guard let couponCellModels = commodityCouponCellModels[commodity.id] else {
            couponSection.couponViewModel?.recentlyCouponModel = nil
            couponSection.couponViewModel?.selectedCouponModel = nil
            selectedCommodity?.selectedCouponModel = nil
            return
        }
        
        // 可使用券优惠条件最低 & 优惠力度最大的(优惠条件一样的情况看优惠力度)
        var recentlyCouponModel: TVCouponCellModel?
        // 优惠力度
        var offPrice: Double = 0
        // 优惠条件
        var amountThreshhold: Double = 0
        // 最低优惠条件
        var recentlyPrice = Double.greatestFiniteMagnitude
        // 最低优惠条件对应优惠力度最大的金额
        var recentlyMaxDisPrice = Double.greatestFiniteMagnitude
        // 最大金额
        let maxNumberPrice = commodity.maxNumberPrice
        // 优惠力度最大
        var maxOffPrice: Double = 0
        for cellModel in couponCellModels {
            offPrice = cellModel.offPrice(priceMulriple)
            amountThreshhold = cellModel.amountThreshhold
            // 可用
            // 优惠条件最小
            // 优惠条件相同 && 优惠力度最大
            if maxNumberPrice >= amountThreshhold &&
                (recentlyPrice > amountThreshhold ||
                 (recentlyPrice == amountThreshhold &&
                  offPrice > recentlyMaxDisPrice)) {
                recentlyPrice = amountThreshhold
                // 最低优惠条件对应优惠力度最大的金额
                recentlyMaxDisPrice = offPrice
                recentlyCouponModel = cellModel
            }
            
            // 判断 是否满足优惠券条件, 不满足跳过下一个
            guard priceMulriple >= amountThreshhold else { continue }
            // 优惠力度最大的
            guard offPrice > maxOffPrice else { continue }
            maxOffPrice = offPrice
            defalutCoupon = cellModel
        }
        // 有满足的券就跳出数量列表了
        couponSection.couponViewModel?.recentlyCouponModel = recentlyCouponModel
        couponSection.couponViewModel?.selectedCouponModel = defalutCoupon
        selectedCommodity?.selectedCouponModel = defalutCoupon
     }
    /**三、选择数量,
     1. 找合适券, 如果找不到券 就是SELECT状态
     */
    func setupCoupon(for numberIndex: Int) {
        guard let commodity = selectedCommodity else { return }
        commodity.selectedNumberIndex = numberIndex

        guard let couponCellModels = commodityCouponCellModels[commodity.id] else {
            couponSection.couponViewModel?.recentlyCouponModel = nil
            couponSection.couponViewModel?.selectedCouponModel = nil
            commodity.selectedCouponModel = nil
            return
        }
        
        let price = commodity.price
        let numberValue = commodity.selectedNumberValue
        let priceMulriple = Double(numberValue) * price
        
        var defalutCoupon: TVCouponCellModel?
        // 可使用券优惠条件最低 & 优惠力度最大的(优惠条件一样的情况看优惠力度)
        var recentlyCouponModel: TVCouponCellModel?
        // 优惠力度
        var offPrice: Double = 0
        // 优惠条件
        var amountThreshhold: Double = 0
        // 最低优惠条件
        var recentlyPrice: Double = CGFloat.greatestFiniteMagnitude
        // 最低优惠条件对应优惠力度最大的金额
        var recentlyMaxDisPrice: Double = 0
        // 最大金额
        let maxNumberPrice = commodity.maxNumberPrice
        // 优惠力度最大
        var maxOffPrice: Double = 0
        for cellModel in couponCellModels {
            offPrice = cellModel.offPrice(priceMulriple)
            amountThreshhold = cellModel.amountThreshhold
            // 可用 && 优惠条件最小 && 优惠力度最大
            if maxNumberPrice >= amountThreshhold &&
                (recentlyPrice > amountThreshhold ||
                 (recentlyPrice == amountThreshhold &&
                  offPrice > recentlyMaxDisPrice)) {
                recentlyPrice = amountThreshhold
                // 最低优惠条件对应优惠力度最大的金额
                recentlyMaxDisPrice = offPrice
                recentlyCouponModel = cellModel
            }
            
            // 判断 是否满足优惠券条件, 不满足跳过下一个
            guard priceMulriple >= amountThreshhold else { continue }
            // 优惠力度最大的
            guard offPrice > maxOffPrice else { continue }
            maxOffPrice = offPrice
            defalutCoupon = cellModel
        }
        // 有满足的券就跳出数量列表了
        couponSection.couponViewModel?.recentlyCouponModel = recentlyCouponModel
        couponSection.couponViewModel?.selectedCouponModel = defalutCoupon
        selectedCommodity?.selectedCouponModel = defalutCoupon
    }

    /**四、选择优惠券
     1. 找到当前规格下面的数量
     */
    func setupNumberIndex(for couponModel: TVCouponCellModel?) {
        guard couponSection.couponViewModel?.selectedCouponModel != couponModel else { return }

        guard let coupon = couponModel else {
            couponSection.couponViewModel?.recentlyCouponModel = nil
            couponSection.couponViewModel?.selectedCouponModel = nil
            selectedCommodity?.selectedCouponModel = nil
            return
        }
        couponCode = coupon.couponCode
        setupDefaultCouponCodeCommodity()
    }
    
    /** 从优惠券进来找到优惠券 */
    private func setupDefaultCouponCodeCommodity() {
        guard let produtct = commoditiesSection.produtctCellModel else { return }
        // 接口返回默认规格, 如果找不到默认规格, 默认规格是数组第一个
        guard let commodity = produtct.selectedCommodity else { return }

        // 1. 接口返回默认规格 有没有可使用的优惠券
        if let defaultCommodity = fixDefaultCouponCodeCommodity(commodities: [commodity]) {
            // 默认规格有可使用的优惠券, 设置成默认规格
            selectedCommodity = defaultCommodity
            return
        }

        // 2. 接口返回默认规格符没有可使用的优惠券,
        // 去规格列表从头开始遍历 依次找到有合适券的对应的规格
        if let defaultCommodity = fixDefaultCouponCodeCommodity(commodities: produtct.commodities) {
            // 规格数组有可使用的优惠券的 规格, 设置成默认规格
            selectedCommodity = defaultCommodity
            return
        }

        // 3. 再没找到 选择默认规格, 优惠券 SELECT状态 数量index按后端接口返回值为准
        selectedCommodity = commodity
        couponSection.couponViewModel?.selectedCouponModel = nil
        selectedCommodity?.selectedCouponModel = nil
    }

    private func fixDefaultCouponCodeCommodity(commodities: [TVCommodityCellModel]) -> TVCommodityCellModel? {
        var defaultCommodity: TVCommodityCellModel?
        var defalutCoupon: TVCouponCellModel?
        for commodity in commodities {
            // 如果规格没有优惠券, 跳过下一个
            guard let couponCellModels = commodityCouponCellModels[commodity.id],
                  !couponCellModels.isEmpty else { continue }

            for coupon in couponCellModels {
                guard coupon.couponCode == couponCode else { continue }
                defalutCoupon = coupon
                break
            }

            guard defalutCoupon != nil else { continue }
            let amountThreshhold = defalutCoupon?.amountThreshhold ?? 0

            // 找到优惠券, 判断当前 规格 * 数量 是否满足 优惠券
            let price = commodity.price
            var numberIndex = -1
            var selectedIndex = -1
            var priceMulriple: Double = 0

            let numbers = commodity.numbers
            for number in numbers {
                numberIndex += 1
                priceMulriple = Double(number) * price
                // 判断是否满足优惠券条件, 不满足跳过下一个
                guard priceMulriple >= amountThreshhold else { continue }
                selectedIndex = numberIndex
                break
            }
            // 有满足的券就跳出数量列表了
            guard selectedIndex >= 0 else { continue }
            _ = defalutCoupon?.offPrice(priceMulriple)
            defaultCommodity = commodity
            defaultCommodity?.selectedNumberIndex = selectedIndex
            couponSection.couponViewModel?.selectedCouponModel = defalutCoupon
            defaultCommodity?.selectedCouponModel = defalutCoupon
            break
        }
        return defaultCommodity
    }
    
    func resetupServicesSection() {
        var services: [TVServiceCellModel] = []
        
        let devServices = AppFunctionManager.dvb
        var key = "\(AppFBConfigType.FB_DVB_RECHARGE.rawValue)"
        if let _ = devServices[key] {
            if AppFunctionManager.validType(function: .FB_RECHARGE_DTH) != .disapper ||
               AppFunctionManager.validType(function: .FB_RECHARGE_DTT) != .disapper {
                let service = TVServiceCellModel(iconName: "commodity_tv_recharge_icon",
                                                 name: OLLocalize("wallet_recharge"),
                                                 targetUrl: STSRouter.urlFor(localPage: .dvbRecharge))
                services.append(service)
            }
        }
        key = "\(AppFBConfigType.FB_DVB_BOUQUET.rawValue)"
        if let _ = devServices[key] {
            // 2个开关打开1个就可以
            if AppFunctionManager.validType(function: AppFBConfigType.FB_BOUQUET_DTH) != .disapper ||
                AppFunctionManager.validType(function: AppFBConfigType.FB_BOUQUET_DTT) != .disapper {
                let service = TVServiceCellModel(iconName: "commodity_tv_bouquet_icon",
                                                 name: OLLocalize("topup_bouquet"),
                                                 targetUrl: STSRouter.urlFor(localPage: .dvbChangeBouquet))
                services.append(service)
            }
        }
        
        key = "\(AppFBConfigType.FB_DVB_ORDER.rawValue)"
        if let _ = devServices[key] {
            let service = TVServiceCellModel(iconName: "commodity_tv_orders_icon",
                                             name: OLLocalize("decoder_subscription_orders"),
                                             targetUrl: STSRouter.urlFor(localPage: .dvbOrder))
            services.append(service)
        }
        
        key = "\(AppFBConfigType.FB_DVB_STATEMENT.rawValue)"
        if let _ = devServices[key] {
            let service = TVServiceCellModel(iconName: "commodity_tv_statement_icon",
                                             name: OLLocalize("account_statement"),
                                             targetUrl: STSRouter.urlFor(localPage: .dvbAccountStatement))
            services.append(service)
        }
        
        serviceSection.services = services
    }
}


extension STCommodityTVViewModel {
    
    // 卡信息模块
    private func responseCardSection() {
        guard let actived = OTTService.shared.activedPackage else {
            cardSection.cardCellModel = nil
            let width = STScreenWidth - 12 * 2
            let font = UIFont.systemFont(ofSize: 12.f_scale)
            let theight = "dvb_activation_notice".localized().st_stringHeight(font: font, maxWidth: width)
            
            var height = 130.ui_scale + theight
            cardSection.cellSize = CGSize(width: width, height: height)
            // print("-->toj: activityModel.phone: \(STUniversalLinksManager.shared.activityModel?.phone)")
            guard STUniversalLinksManager.shared.activityModel != nil
            else { return }
            height = width * 328 / 336
            cardSection.cellSize = CGSize(width: width, height: height)
            return
        }
        
        if let card = DVBService.shared.linkCard {
            let cardModel = TVCardCellModel(card: card)
            cardSection.cardCellModel = cardModel
        } else {
            let cardModel = TVCardCellModel(actived: actived)
            cardSection.cardCellModel = cardModel
        }
        
        let width = STScreenWidth - 12 * 2
        let height = width * 152 / 336
        cardSection.cellSize = CGSize(width: width, height: height)
    }
    
    // MARK: - TV规格模块
    private func responseComoditiesSection(smartcardInfo: TVSmartcardInfo?) {
        let section = commoditiesSection
        guard let cardInfo = smartcardInfo else {
            section.produtctCellModel = nil
            return
        }
        
        let produtctCellModel = TVProductCellModel(cardInfo: cardInfo)
        section.produtctCellModel = produtctCellModel
        sections.append(section)
    }

    // MARK: - 加购模块
    private func responsePurchaseSection(chargeInfo: TVRechargeInfo?) {
        guard let additionals = chargeInfo?.additionalRules,
              let items = chargeInfo?.smartcardInfo?.recharge_items,
              !additionals.isEmpty,
              !items.isEmpty
                 else {
            return
        }
        
        var additionalDictionary = [String: TVAdditionalRulesModel]()
        additionals.forEach { additional in
            //let purchase = TVPurchaseCellModel(additional: additionalRulesModel)
            let additionalID = additional.additionalRuleId
            guard !additionalID.isEmpty else { return }
            additionalDictionary[additionalID] = additional
        }
        
        var purchaseCommodityDictionary = [String: TVPurchaseCellModel]()
        items.forEach { item in
            guard !item.additionalRuleId.isEmpty else { return }
            let additionalRuleId = item.additionalRuleId
            guard let additional = additionalDictionary[additionalRuleId] else { return }
            let purchase = TVPurchaseCellModel(additional: additional)
            let commodityID = item.id
            purchaseCommodityDictionary[commodityID] = purchase
        }
        
        purchaseDictionary = purchaseCommodityDictionary
        
        
        let section = purchaseSection
        sections.append(section)
    }
    
    // MARK: - 支付渠道模块
    private func responseCommodityChannelSection(orderInf: TVPreOrderInfo?) {
        guard let payChannels = orderInf?.payChannels else { return }
        
        let section = channelsSection
        let channelModel = TVChannelsViewModel(payChannels: payChannels)
        channelModel.selectedChannel = channelModel.defaultChannel
        channelModel.isOpened = orderInf?.payShow ?? false
        section.channelCellModel = channelModel
        
        let channelCount = channelModel.channels.count
        let fheight = channelCount <= 1 ? 30.ui_scale : 64.ui_scale
        section.footerSize = CGSize(width: STScreenWidth, height: fheight)
        
        sections.append(section)
    }
    
    // 优惠券模块
    private func responseCounponSection(orderInf: TVPreOrderInfo?) {
        guard let coupons = orderInf?.coupons, !coupons.isEmpty,
                let items = orderInf?.rechargeItems, !items.isEmpty else { return }
        
        let section = couponSection
        
        var couponsDictionary = [String: TVCouponCellModel]()
        var cellModels = [TVCouponCellModel]()
        coupons.forEach { coupon in
            let cellModel = TVCouponCellModel(coupon: coupon)
            cellModels.append(cellModel)
            
            let couponCode = coupon.promotion_coupon_instance_code
            couponsDictionary[couponCode] = cellModel
        }
        
        // 所有的优惠券
        let couponViewModel = TVCouponViewModel(models: cellModels)
        section.couponViewModel = couponViewModel
        sections.append(section)
        
        // 规格id 对应的优惠券列表
        var couponDictionary = [String: [TVCouponCellModel]]()
        items.forEach { item in
            let id = item.id
            let couponCodes = item.couponCodes
            guard !couponCodes.isEmpty else { return }
            var commodityCouponList = [TVCouponCellModel]()
            couponCodes.forEach { code in
                guard let cellModel = couponsDictionary[code] else { return }
                commodityCouponList.append(cellModel)
            }
            couponDictionary[id] = commodityCouponList
        }
        commodityCouponCellModels = couponDictionary
    }
    
    private func responseServicesSection() {
        resetupServicesSection()
        sections.append(serviceSection)
    }

    // 用户服务协议模块
    private func responseServiceSection() {
        let commodityCount =  commoditiesSection.produtctCellModel?.commodities.count ?? 0
        guard commodityCount > 0 else { return }
        
        let section = STCommodityTVSectionModel()
        section.type = .serviceAgreement
        section.isImage = false
        section.headerSize = STDefaultCellSize
        section.footerSize = STDefaultCellSize
        section.cellSize = CGSize(width: STScreenWidth, height: 52.ui_scale)
        sections.append(section)
    }
}

extension STCommodityTVViewModel {
    
    func requestCardInfo(completion: ((_ isSuccess: Bool, _ message: String)->Void)? = nil) {
        let isLinkCard = AppFunctionManager.isUsable(function: .FB_DVB_ACTIVATION)
        guard isLinkCard else {
            resetupSections()
            return
        }
        
        requestFetchOTTStatus(completion: completion)
    }
    
    private func requestFetchOTTStatus(completion: ((_ isSuccess: Bool, _ message: String)->Void)? = nil) {
        OTTService.shared.fetchOTTStatus(success: { [weak self] in
            guard let dvbService = OTTService.shared.activedPackage else {
                completion?(false, "")
                self?.resetupSections()
                return
            }
            
            self?.dvbState = dvbService.status
            self?.fetchCardInfo(cardNo: dvbService.smartcard, completion: completion)
        }) { [weak self] (message) in
            completion?(false, message)
            self?.resetupSections()
        }
    }
    
    func fetchCardInfo(cardNo: String, completion: ((_ isSuccess: Bool, _ message: String)->Void)? = nil) {
        provider.sendRequest(STSDVBApi.getSmartCardDetail(cardNo: cardNo)) { [weak self] (result: STResult<DVBSmartCardDetail, MoyaError>) in
            var message = OLLocalize("network_error")
            var success = false
            switch result {
            case let .success(value):
                message = ""
                success = true
                DVBService.shared.cards[cardNo]?.setCardDetail(with: value)
                DVBService.shared.linkCard = value
            case .failure(_):
                break
            }
            completion?(success, message)
            self?.resetupSections()
            guard success else {
                return
            }
            self?.requestSmartCardRechargeInfo(smartcard: cardNo, completion: completion)
        }
    }
    
    func requestSmartCardRechargeInfo(smartcard: String, completion: ((_ isSuccess: Bool, _ message: String)->Void)? = nil) {
        provider.sendRequest(STSDVBApi.smartCardRechargeInfo(cardNo: smartcard)) { [weak self] (result: STResult<STModel<TVRechargeInfo>, MoyaError>) in
            
            var message = OLLocalize("network_error")
            var success = false
            switch result {
            case let .success(value):
                message = ""
                success = true
                self?.chargeInfo = value.data
            case .failure(_):
                break
            }
            completion?(success, message)
            self?.resetupSections()
        }
    }
    
    // 解除绑卡状态
    func requestUnlink(completion: ((_ isSuccess: Bool)->Void)? = nil)  {
        provider.sendRequest(STSDVBApi.unlink) { [weak self] (result: STResult<Deactivate, MoyaError>) in
            var isSuccess = false
            switch result {
            case let .success(value):
                if value.code == .success {
                    DVBService.shared.linkCard = nil
                    isSuccess = true
                }
            default:
                break
            }
            completion?(isSuccess)
            self?.resetupSections()
        }
    }
}
